import { useUserStore } from '@/store/userStore.js';
import { encrypt, decrypt } from '@/utils/aes.js';

const userStore = useUserStore();
const env = wx.getAccountInfoSync().miniProgram.envVersion;

const Hosts = {
  develop: 'https://pct.leshua.top',
  trial: 'https://pct.leshua.top',
  release: '',
};

const baseUrl = Hosts[env];

export { baseUrl };

export function request(options) {
  let { method = 'GET', data = {}, url, type, serviceBase = '/smt-shopping', encryptionType, expireNeedJump = true } = options;

  let contentType = getContentType(type);

  let headers = {
    Accept: 'application/json, text/plain, */*',
    'Content-Type': contentType,
  };

  // 处理 token
  let token = userStore.access_token
    ? userStore.access_token
    : uni.getStorageSync('access_token')
    ? uni.getStorageSync('access_token')
    : false;
  if (token) {
    headers['Authorization'] = token;
  }

  let requestData = data;
  if (encryptionType == 'aes') {
    requestData = encodeURIComponent(encrypt(JSON.stringify(data), userStore.UserAccessInfo.encryptKey));
  }
  // 发起请求
  return new Promise((resolve, reject) => {
    uni.request({
      url: baseUrl + serviceBase + url,
      method,
      header: headers,
      timeout: 20000, //超时时间20秒
      data: requestData,
      success(res) {
        console.group('------------->request<-------------');
        console.log('+++++++++++8848猴赛雷start+++++++++++');
        console.info('请求地址--------->', url);
        console.info('请求参数--------->', data);
        console.info('响应数据--------->', res.data);

        // 登录过期
        if (res.data.code == 401 && expireNeedJump) {
          // uni.showToast({
          //   title: '登录超时，请重新登录',
          //   icon: 'none',
          //   duration: 2000,
          // });
          userStore.clearAll();
          userStore.$reset(); // 清空用户信息
          setTimeout(() => {
            uni.reLaunch({
              url: '/subPages/login/index',
            });
          }, 0);
        }

        // 请求报错提示
        if (res.data.code != 0 && res.data.code != 401) {
          uni.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 2000,
          });
        }

        let result = res.data;
        if (res.data.data && encryptionType == 'aes') {
          result.data = JSON.parse(
            decrypt(decodeURIComponent(res.data.data || ''), userStore.UserAccessInfo.encryptKey),
          );
          console.info('解密数据--------->', result);
        }
        console.log('+++++++++++8848猴赛雷end+++++++++++');
        console.groupEnd();
        resolve(result);
      },
      fail(err) {
        reject(err);
      },
    });
  });
}

// 获取请求头内容类型
function getContentType(type) {
  let contentType;
  switch (type) {
    case 1:
      contentType = 'application/x-www-form-urlencoded';
      break;
    case 2:
      contentType = 'multipart/form-data';
      break;
    default:
      contentType = 'application/json;charset=UTF-8';
  }
  return contentType;
}
